#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
// #include "esp_spi_flash.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_wifi.h"
#include "esp_http_client.h"

#include "st7735.h"
#include "wifi-http.h"
#include "sntp_time.h"
#include "esp_heap_caps.h"

// 合宙esp32c3 boot键
#define BOOT_BUTTON_GPIO GPIO_NUM_9
// HTTP URL
#define IMAGE_URL "http://10.96.200.252:8000/.esp32jpg/test%d.jpg"
#define DELAYSWITCH 10

#define TAG "MAIN"
void downloadAndShowPhoto(){
    char url_buffer[255];
    static int picnum=-1;

    if(!wifi_connected) return;
    if(needRenderPhoto) return; //last photo still waiting render
    picnum++;
    snprintf(url_buffer,255,IMAGE_URL,picnum);
    ESP_LOGI(TAG,"%s",url_buffer);
    // 初始化 HTTP 客户端并下载图片
    esp_http_client_config_t config;
    bzero(&config,sizeof(config));
    config.url = url_buffer;
    config.event_handler = http_event_handler;
    
    esp_http_client_handle_t client = esp_http_client_init(&config);
    http_request_failed=false;
    esp_err_t err = esp_http_client_perform(client);
    if (err == ESP_OK) {
        ESP_LOGI(TAG, "Image downloaded.");
    } else {
        ESP_LOGE(TAG, "HTTP request failed: %s", esp_err_to_name(err));
        picnum=-1;
        http_request_failed=true;
    }
    esp_http_client_cleanup(client);
    if(http_request_failed) {
        picnum=-1;
    }
    return;
}

extern "C" void app_main(void) {
    // 初始化 NVS
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);
    
    // 初始化 Wi-Fi 和 HTTP
    wifi_init();

    // gpio_init();
    initializeSpi();
    initializeLcd();
    initializeLVGL();
    settingUI();

    /*
    // 等待连接成功
    while (!wifi_connected) {
        vTaskDelay(500 / portTICK_PERIOD_MS);
        ESP_LOGI(TAG, "Waiting for Wi-Fi connection...");
    }
    */
    showMsg("Starting...");
    // wait wifi
    while(1){
        if(!wifi_connected) {
            ESP_LOGI(TAG,"wait for wifi connecting...");
            lv_timer_handler();
            vTaskDelay(1000 / portTICK_PERIOD_MS);         
        } else break;
    }
    // first photo
    downloadAndShowPhoto();
    //if(!sntp_ready) 
    initialize_sntp();
    
    while(1){
        renderPhoto();        
        int delaySwitch=0;
        // every DELAYSWITCH (10second) switch a photo
        while(1){
            // 获取当前堆的剩余大小
            size_t free_heap_size = esp_get_free_heap_size();
            ESP_LOGI(TAG, "Free heap size: %d bytes, loop %d", 
                free_heap_size,delaySwitch);

            lv_timer_handler();

            vTaskDelay(1000 / portTICK_PERIOD_MS);

            downloadAndShowPhoto();
            
            if (gpio_get_level(BOOT_BUTTON_GPIO) == 0) {  // 按下时为低电平
                ESP_LOGI(TAG, "Boot button pressed!");
                break;
            }
            
            if(delaySwitch++ >= DELAYSWITCH){
                break;
            }
        }
    };
}
